<?php
/**
 *
 * @package avp
 * @version $Id: $
 * @copyright (c) 2006 Jan-Willem van Ganswijk, Stefan van Essen
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

define( 'IN_SCRIPT', 'TRUE' ); //Voor de evil haxx0rz.

$root = '../';

include( $root . 'includes/common.inc.php' );
include( $root . 'includes/lang.inc.php' );
include( $root . 'includes/session.class.php' );
include( $root . 'includes/admin.inc.php' );
include( $root . 'includes/template.class.php' );

$session = new sessionWrapper();
$lang = read_langfiles( 'admin_common,admin_avatar' );
$template = new template( $CONFIG['theme'] );
$template->add_var( 'active', 'avatars' );

if ( !$session->check_login() ) {
    die( print_error( $lang['ERROR_NEEDLOGIN'], 'login.php', true ) );
}

$action = addslashes( $_GET['action'] );

if ( $action == 'list' || empty( $action ) ) {
    $sort = addslashes( $_GET['sort'] );
    switch ( $sort ) {
        case 'name_down':
            $sort_clause = "ORDER BY `name` DESC";
            break;
        case 'requests_up':
            $sort_clause = "ORDER BY `requestcount` DESC";
            break;
        case 'requests_down':
            $sort_clause = "ORDER BY `requestcount` ASC";
            break;
        case 'name_up':
        default:
            $sort_clause = "ORDER BY `name` ASC";
            break;
    }
    /**
     * Pagination Logic
     */
    $total = $db->query_first( "SELECT COUNT(`id`) AS total FROM `" . $db->get_table( "avatar" ) . "`" );
    $total = $total['total'];
    if( $total == 0 ) {
        $totalpages = 1;
    } else {
        $totalpages = ceil( $total / $CONFIG['per_page'] );
    }

    $page = addslashes( $_GET['page'] );
    if( $page > 1 ) {
        $limit_clause = 'LIMIT ' . ( ( $page - 1 ) * $CONFIG['per_page'] ) . ',' . ( $page * $CONFIG['per_page'] );
    } else {
        $limit_clause = 'LIMIT 0,' . $CONFIG['per_page'];
        $page = 1;
    }

    $pagination = '';
    for( $i = 1 ; $i <= $totalpages ; $i++ ) {
        if( $i == $page ) {
            $pagination .= "<b>{$i}</b> ";
        } else {
            $pagination .= "<a href=\"{$_SERVER[PHP_SELF]}?page={$i}\">{$i}</a> ";
        }
    }

    $result = $db->query( "SELECT * FROM `" . $db->get_table( "avatar" ) . "` {$sort_clause} {$limit_clause}" );

    while ( $row = $db->fetch( $result ) ) {
        if($CONFIG['mod_rewrite'] == 1) {
        $row['url'] = $CONFIG['webpath'] . 'avatar-' . $row['id'] . '.' . $row['output_format'];
        } else {
                    $row['url'] = $CONFIG['webpath'] . 'avatar.php?id=' . $row['id'];
        }
        $template->append( 'avatars', $row );
    }
    $template->add_var( 'pagination', $pagination );
    $template->set_title( $lang['TITLE_LIST_AVATARS'] );
    $template->add_templates( 'admin_header,admin_avatar_list,admin_footer' );
    $template->make_page();
    exit;
} elseif ( $action == 'manage' ) {
    $id = addslashes( $_GET['id'] );

    if ( $id < 0 || !isset( $_GET['id'] ) ) {
        print_error( $lang['ERROR_NOID'], $_SERVER['PHP_SELF'] );
        exit;
    }

    if ( isset( $_GET['addimage'] ) ) {
        if ( $_POST['sourceimageid'] < 0 ) {
            print_error( $lang['ERROR_MISSING_DATA'], $_SERVER['PHP_SELF'] . "?action=edit&id={$id}" );
            exit;
        }
        if( strstr( $_POST['sourceimageid'], 'p' ) ) {
            $pluginid = explode( '-', $_POST['sourceimageid'] );
            $pluginid = $pluginid[1];
            $sql = "INSERT INTO `" . $db->get_table( 'sets' ) . "` (`pluginid`,`imageid`,`avatarid`) VALUES ('" . $pluginid . "','-1','{$id}')";
        } else {
            $sql = "INSERT INTO `" . $db->get_table( 'sets' ) . "` (`imageid`,`avatarid`) VALUES ('" . $_POST['sourceimageid'] . "','{$id}')";
        }
        $db->query( $sql );
        header( "location: " . $_SERVER['PHP_SELF'] . "?action=manage&id={$id}" );
        exit;
    } elseif ( isset( $_GET['deleteimage'] ) ) {
        if ( $imgdata = $db->query_first( "SELECT * FROM `" . $db->get_table( 'sets' ) . "` WHERE `setid`='{$id}'" ) ) {
            $db->query( "DELETE FROM `" . $db->get_table( "sets" ) . "` WHERE `setid`='{$id}'" );
            header( "location: " . $_SERVER['PHP_SELF'] . "?action=manage&id=" . $imgdata["avatarid"] . "" );
        } else {
            print_error( $lang['ERROR_MISSING_DATA'], $_SERVER['PHP_SELF'] );
            exit;
        }

        exit;
    } elseif ( isset( $_GET['resetstats'] ) ) {
        $db->query( "UPDATE `" . $db->get_table( "avatar" ) . "` SET `timer_total`='0', `timer_times`='0',`requestcount`='0' WHERE `id`='{$id}' LIMIT 1" );
        header( "location: " . $_SERVER['PHP_SELF'] . "?action=manage&id={$id}" );
        exit;
    }

    $result = $db->query( "SELECT `imagename`,`imageid` FROM `" . $db->get_table( "images" ) . "` ORDER BY `imagename`" );
    $available_images = array();
    while ( $imagerow = $db->fetch( $result ) ) {
        $available_images[$imagerow['imageid']] = $imagerow['imagename'];
    }
    $db->free_result( $result );

    $result = $db->query( "SELECT `name`,`pluginid` FROM `" . $db->get_table( "plugins" ) . "` ORDER BY `name`" );
    while ( $pluginrow = $db->fetch( $result ) ) {
        $available_images['p-' . $pluginrow['pluginid']] = $pluginrow['name'] . ' (plugin)';
    }
    $db->free_result( $result );

    $result = $db->query( "SELECT i.`imagename`, s.`setid`, s.`imageid`, s.`pluginid`
                           FROM `" . $db->get_table( "sets" ) . "` AS s
                           LEFT JOIN `" . $db->get_table( "images" ) . "` AS i
                           USING(`imageid`)
                           WHERE `avatarid`='{$id}'" );
    while ( $imagerow = $db->fetch( $result ) ) {
        if( $imagerow['imageid'] < 0 ) {
            $imagerow['thumbarg'] = 'pluginid=' . $imagerow['pluginid'];
        } else {
            $imagerow['thumbarg'] = 'imageid=' . $imagerow['imageid'];
        }
        $template->append( 'current_images', $imagerow );
    }
    $db->free_result( $result );

    $values = $db->query_first( "SELECT * FROM `" . $db->get_table( "avatar" ) . "` WHERE `id`='" . $id . "' LIMIT 1" );

    if ( $values['timer_times'] > 0 ) {
        $values['maketime'] = round( ( $values['timer_total'] / ( $values['timer_times'] ) ), 3 );
    } else {
        $values['maketime'] = 0;
    }

    if ( $values['hc_mode'] == 'passive' ) {
        $result = $db->query( "SELECT * FROM `" . $db->get_table( "hotlinkcheck" ) . "` WHERE `avatarid`='{$id}'" );
        while ( $hc_row = $db->fetch( $result ) ) {
            if( $hc_row['hc_allow'] == 1 ) {
                $hc_row['hc_actionurl'] = 'avatar.php?action=hcedit&block&id=' . $hc_row['hc_id'];
                $hc_row['hc_actionstr'] = $lang['LINK_BLOCK'];
            } else {
                $hc_row['hc_actionurl'] = 'avatar.php?action=hcedit&unblock&id=' . $hc_row['hc_id'];
                $hc_row['hc_actionstr'] = $lang['LINK_UNBLOCK'];
            }
            $template->append( 'hc_detected', $hc_row );
        }
    }
    $template->set_title( $lang['TITLE_MANAGE_AVATAR'] );

    $template->add_var( 'available_images', $available_images );
    $template->add_var( 'values', $values );

    $template->add_templates( 'admin_header,admin_avatar_manage,admin_footer' );
    $template->make_page();
    exit;
} elseif ( $action == 'edit' ) {
    $id = addslashes( $_GET['id'] );

    if ( $id < 0 || !isset( $_GET['id'] ) ) {
        print_error( $lang['ERROR_NOID'], $_SERVER['PHP_SELF'] );
        exit;
    }

    if ( isset( $_GET['submit'] ) ) {
        if ( empty( $_POST['name'] ) || empty( $_POST['size_height'] ) || empty( $_POST['size_width'] ) || empty( $_POST['output_format'] ) ) {
            print_error( $lang['ERROR_MISSING_DATA'], $_SERVER['PHP_SELF'] . "?action=edit&id={$id}" );
            exit;
        }

        $db->query( "UPDATE `" . $db->get_table( "avatar" ) . "`
		SET
		`name`='" . addslashes( $_POST["name"] ) . "',
		`size_height`='" . addslashes( $_POST["size_height"] ) . "',
		`size_width`='" . addslashes( $_POST["size_width"] ) . "',
		`output_format`='" . addslashes( $_POST["output_format"] ) . "',
		`resize_mode`='" . addslashes( $_POST["resize_mode"] ) . "'
		WHERE `id`='{$id}' LIMIT 1
		" );

        print_message( $lang['TITLE_EDIT_AVATAR'], $lang['MSG_EDITED'], $_SERVER['PHP_SELF'] . "?action=manage&id={$id}" );
        exit;
    }

    $row = $db->query_first( "SELECT * FROM `" . $db->get_table( "avatar" ) . "` WHERE `id`='" . $id . "' LIMIT 1" );

    $imgformats = array( 'png' => 'PNG', 'jpg' => 'JPEG', 'gif' => 'GIF' );
    $resize_modes = array( 'resample' => 'Resample', 'resize' => 'Resize', 'copy' => 'Copy' );

    $template->set_title( $lang['TITLE_EDIT_AVATAR'] );

    $template->add_var( 'imgformats', $imgformats );
    $template->add_var( 'resize_modes', $resize_modes );
    $template->add_var( 'formurl', $_SERVER['PHP_SELF'] . '?action=edit&submit&id=' . $row['id'] );
    $row['mode'] = 'edit';
    $template->add_var( 'values', $row );

    $template->add_templates( 'admin_header,admin_avatar_add,admin_footer' );
    $template->make_page();

    exit;
} elseif ( $action == 'add' ) {
    if ( isset( $_GET['submit'] ) ) {
        if ( empty( $_POST['name'] ) || empty( $_POST['size_height'] ) || empty( $_POST['size_width'] ) || empty( $_POST['output_format'] ) ) {
            print_error( $lang['ERROR_MISSING_DATA'], $_SERVER['PHP_SELF'] . "?action=edit&id={$id}" );
            exit;
        }
        $db->query( "INSERT INTO `" . $db->get_table( "avatar" ) . "` (`name`,`size_height`,`size_width`,`output_format`,`resize_mode`)
			VALUES(
			'" . addslashes( $_POST['name'] ) . "',
			'" . addslashes( $_POST['size_height'] ) . "',
			'" . addslashes( $_POST['size_width'] ) . "',
			'" . addslashes( $_POST['output_format'] ) . "',
			'" . addslashes( $_POST['resize_mode'] ) . "'
			)" );

        $id = $db->get_insert_id();

        print_message( $lang['TITLE_ADD_AVATAR'], $lang['MSG_ADDED'], $_SERVER['PHP_SELF'] . "?action=manage&id={$id}" );
        exit;
    }
    $imgformats = array( 'png' => 'PNG', 'jpg' => 'JPEG', 'gif' => 'GIF' );
    $resize_modes = array( 'resample' => 'Resample', 'resize' => 'Resize', 'copy' => 'Copy' );

    $template->set_title( $lang['TITLE_ADD_AVATAR'] );

    $template->add_var( 'imgformats', $imgformats );
    $template->add_var( 'resize_modes', $resize_modes );
    $template->add_var( 'formurl', $_SERVER['PHP_SELF'] . '?action=add&submit' );

    $template->add_templates( 'admin_header,admin_avatar_add,admin_footer' );
    $template->make_page();
    exit;
} elseif ( $action == 'delete' ) {
    $id = addslashes( $_GET['id'] );
    if ( $id < 0 || !isset( $_GET['id'] ) ) {
        print_error( $lang['ERROR_NOID'], $_SERVER['PHP_SELF'] );
        exit;
    }
    if ( isset( $_GET['submit'] ) ) {
        if ( $db->query_first( "SELECT * FROM `" . $db->get_table( "avatar" ) . "` WHERE id='{$id}' LIMIT 1" ) ) {
            $db->query( "DELETE FROM `" . $db->get_table( "avatar" ) . "` WHERE id='{$id}' LIMIT 1" );
            $db->query( "DELETE FROM `" . $db->get_table( "sets" ) . "` WHERE avatarid='{$id}'" );

            print_message( $lang['TITLE_DELETE_AVATAR'], $lang['MSG_DELETED'], $_SERVER['PHP_SELF'] );
        } else {
            print_error( $lang['ERROR_MISSING_DATA'], $_SERVER['PHP_SELF'] );
            exit;
        }
        exit;
    }
    print_confirmbox( $_SERVER['PHP_SELF'] . "?action=delete&submit&id={$id}", $_SERVER['PHP_SELF'] );
    exit;
} elseif ( $action == 'hcedit' ) {
    $id = addslashes( $_GET['id'] );
    if ( $id < 0 || !isset( $_GET['id'] ) ) {
        print_error( $lang['ERROR_NOID'], $_SERVER['PHP_SELF'] );
        exit;
    }
    if ( isset( $_GET['submit'] ) ) {
        $domains = trim( addslashes( $_POST['hc_domains'] ) );
        $db->query( "UPDATE `" . $db->get_table( "avatar" ) . "` SET `hc_mode`='" . addslashes( $_POST['hc_mode'] ) . "',`hc_domains`='" . $domains . "' WHERE `id`='{$id}' LIMIT 1" );
        print_message( $lang['TITLE_EDIT_AVATAR'], $lang['MSG_HCEDITED'], $_SERVER['PHP_SELF'] . "?action=manage&id={$id}" );
        exit;
    }
    if ( isset( $_GET['block'] ) ) {
        if ( $row = $db->query_first( "SELECT `avatarid` FROM `" . $db->get_table( "hotlinkcheck" ) . "` WHERE `hc_id`='{$id}'" ) ) {
            $db->query( "UPDATE `" . $db->get_table( "hotlinkcheck" ) . "` SET `hc_allow`='0' WHERE `hc_id`='{$id}'" );
        }
        header( "location: " . $_SERVER['PHP_SELF'] . "?action=manage&id=" . $row['avatarid'] . "" );
        exit;
    }
    if ( isset( $_GET['unblock'] ) ) {
        if ( $row = $db->query_first( "SELECT `avatarid` FROM `" . $db->get_table( "hotlinkcheck" ) . "` WHERE `hc_id`='{$id}'" ) ) {
            $db->query( "UPDATE `" . $db->get_table( "hotlinkcheck" ) . "` SET `hc_allow`='1' WHERE `hc_id`='{$id}'" );
        }
        header( "location: " . $_SERVER['PHP_SELF'] . "?action=manage&id=" . $row['avatarid'] . "" );
        exit;
    }
    if ( isset( $_GET['delete'] ) ) {
        if ( $row = $db->query_first( "SELECT `avatarid` FROM `" . $db->get_table( "hotlinkcheck" ) . "` WHERE `hc_id`='{$id}'" ) ) {
            $db->query( "DELETE FROM `" . $db->get_table( "hotlinkcheck" ) . "` WHERE `hc_id`='{$id}'" );
        }
        header( "location: " . $_SERVER['PHP_SELF'] . "?action=manage&id=" . $row['avatarid'] . "" );
        exit;
    }
    $values = $db->query_first( "SELECT * FROM `" . $db->get_table( "avatar" ) . "` WHERE `id`='" . $id . "' LIMIT 1" );
    $hc_modes = array( 'none' => 'Disable Protection', 'passive' => 'Enable Passive Protection', 'active' => 'Enable Active Protection' );

    $template->set_title( $lang['TITLE_EDIT_AVATAR'] );

    $template->add_var( 'values', $values );
    $template->add_var( 'hc_modes', $hc_modes );

    $template->add_templates( 'admin_header,admin_avatar_hcedit,admin_footer' );
    $template->make_page();
}

?>